﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoldierCatchGoal : MonoBehaviour
{
    public Transform trans;
    public GameObject goalObj;
    private float distance;
    private bool isHold;
    private Vector3 lastHoldPos;
    // Start is called before the first frame update
    void Start()
    {
        trans = this.GetComponent<Transform>();
        isHold = false;
        goalObj = GameObject.Find("Goal");
    }

    // Update is called once per frame
    void Update()
    {
        UpdateDistance();
        if (isHold == false && Tag.goalIsLocked == false && distance < 0.34f)
        {
            isHold = true;
            lastHoldPos = trans.position;
            Tag.goalIsLocked = true;
            gameObject.GetComponent<RoadSelector>().GoStart();
            gameObject.GetComponent<BattleObject>().SetBuff(new BuffInfo(4, 1.5f, -1));
            MessageController.Instance.SendMsg("水晶被抢走了!快去抢回来!");
        }
        if (isHold == true)
        {
            float holdDist = Function.DistanceIgnoreZ(trans.position, lastHoldPos);
            lastHoldPos = trans.position;
            gameObject.GetComponent<BattleObject>().addGoalScore(holdDist);
            goalObj.transform.position = trans.position;
            MapManager.Instance.SetGoalPos((Function.WorldPosToLogicPos(goalObj.transform.position.x, goalObj.transform.position.y)));
        }
    }

    public void UpdateDistance()
    {
        distance = Function.DistanceIgnoreZ(trans.position, goalObj.transform.position);
    }
    public bool IsHold()
    {
        return isHold;
    }

    public void OnDestroy()
    {
        if (isHold)
            Tag.goalIsLocked = false;
    }
}
